﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using tutors_clus.Models;
using WebMatrix.WebData;


namespace tutors_clus.Controllers
{
    [Authorize(Roles = "Teacher")]
    public class TeacherController : Controller
    {
        tutors_clubContext db = new tutors_clubContext();
        
        public TeacherController(){
                int id_tea = WebSecurity.CurrentUserId;
                ViewBag.list_course = db.courses.Where(c => c.id_tea == id_tea);
            
        }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Create_Class()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create_Class(course course)
        {
            if (ModelState.IsValid)
            {
                //course cou = new course();
                course.id_tea = WebSecurity.GetUserId(User.Identity.Name);
                course.createdate_cou = DateTime.Now;
                course.registered_num = 0;
                course.status_cou = true;
                db.courses.Add(course);
                db.SaveChanges();
            }
            return RedirectToAction("Manager_Class");
        }
        //Quan ly danh sach lop cua moi giao vien
        public ActionResult Manager_Class()
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var list_course = db.courses.Where(c => c.id_tea == id).OrderByDescending(c=>c.id_cou);
            return View(list_course);
        }
        //Thai doi trang thang lop
        public PartialViewResult Change_status(int id)
        {
            var find_news = db.courses.Find(id);
            if (find_news.status_cou == true)
            {
                find_news.status_cou = false;
            }
            else
            {
                find_news.status_cou = true;
            }
            db.Entry(find_news).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find_news);
        }
        //sua thong tin lop
        public ActionResult Edit_course(int id)
        {
            try
            {
                int id_tea = WebSecurity.GetUserId(User.Identity.Name);
                var course = db.courses.Where(c => c.id_cou == id && c.id_tea == id_tea).FirstOrDefault();//db.courses.Find(id);
                if (course == null)
                {
                    return HttpNotFound();
                }
                return View(course);
            }
            catch (Exception)
            {
                return HttpNotFound();
                throw;
            }           
        }
        //luu lai thong tin lop 
        [HttpPost]
        public ActionResult Edit_course(course cou)
        {
            if (ModelState.IsValid)
            {

                db.Entry(cou).State = EntityState.Modified;
                db.SaveChanges();
            }
            return View(cou);
        }

        //Xoa lop 
        public ActionResult Delete_course(int id)
        {
            var course = db.courses.Find(id);
            db.courses.Remove(course);
            db.SaveChanges();
            return RedirectToAction("Manager_Class");
        }
        //xem thong tin chi tiet lop hoc
        public ActionResult Detail_course(int id)
        {
            var detail = db.courses.Find(id);
            return View(detail);
        }

        //thong tin tung lop hoc cua GV, quan ly comment và message
        public ActionResult My_course(int id)
        {
            var course = db.courses.Find(id);
            return View(course);
        }

        //Dach sách comment theo lop
        public ActionResult Comment_Of_Course(int id_course)
        {
            ViewBag.course = id_course;
            var com = db.comments.Where(c => c.id_cou == id_course && c.parent == 0);
            return View(com);
        }

        //them chu de binh luan cho lop
        public ActionResult Add_Comment_Of_course(int id_course)
        {
            ViewBag.course = db.courses.Find(id_course);

            return View();

        }
        [HttpPost]
        public ActionResult Add_Comment_Of_course(int id_course, string contentCom, string titleCom)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.courses.Where(m => m.id_cou == id_course && m.id_tea == id).Count();
            var comment = db.comments.Where(i => i.id_cou == id_course && i.parent == 0);
            if (check <= 0 || comment == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!String.IsNullOrEmpty(contentCom) && !String.IsNullOrEmpty(titleCom))
                    {
                        comment com = new comment();
                        //com.id_com = id_com;
                        com.id_cou = id_course;
                        com.content_com = contentCom;
                        com.createdate = DateTime.Now;
                        com.title_com = titleCom;
                        com.parent = 0;
                        string[] role = Roles.GetRolesForUser(User.Identity.Name);
                        if (role.Contains("Student"))
                        {
                            com.id_stu = id;
                            com.isrepply = false;
                        }
                        else
                        {
                            com.id_stu = null;
                            com.isrepply = true;
                        }
                        db.comments.Add(com);
                        db.SaveChanges();
                    }
                }
            }
            return RedirectToAction("Comment_Of_Course", new { id_course = id_course });
        }

        public ActionResult Comment_Detail(int id_course, int id_com)
        {
            var dcom = db.comments.Where(c=>c.id_com==id_com);
            var detail = db.comments.Where(c => c.parent == id_com);
            ViewBag.detail_comment = detail;
            ViewBag.count = detail.Count();
            return View(dcom);
        }

        [ValidateInput(false)]
        public ActionResult Add_detail_com(int id_cou, int id_com, string contentCom)
        {
            
            if (ModelState.IsValid)
            {
                if (!String.IsNullOrEmpty(contentCom))
                {
                    comment com = new comment();
                    //com.id_com = id_com;
                    com.id_cou = id_cou;
                    com.content_com = contentCom;
                    com.createdate = DateTime.Now;
                    com.title_com = null;
                    com.parent = id_com;
                    string[] role = Roles.GetRolesForUser(User.Identity.Name);
                    if (role.Contains("Student"))
                    {
                        com.id_stu = WebSecurity.CurrentUserId;
                        com.isrepply = false;
                    }
                    else
                    {
                        com.id_stu = null;
                        com.isrepply = true;
                    }
                    db.comments.Add(com);
                    db.SaveChanges();
                }
            }
            
           return RedirectToAction("Comment_Detail", new { id_course = id_cou, id_com = id_com });
        }

        //Tin nhan theo lop cua 1 giao vien
        public ActionResult Message_Of_Course(int id_course)
        {
            int linh = id_course;
            var mes = db.messages.Where(m => m.id_cou == id_course && m.parent==0).OrderByDescending(m => m.id_mes);
            return View(mes);
        }

        //Xem chi tiet tin nhan cua hs va tra loi
        public ActionResult Message_Detail(int id_course,int id_mes)
        {
            var dmes = db.messages.Where(c => c.id_mes == id_mes);
            var detail = db.messages.Where(c => c.parent == id_mes);
            ViewBag.detail_mes = detail;
            ViewBag.count = detail.Count();
            return View(dmes);
        }
        //[ValidateInput(false)]
        //public ActionResult Add_detail_mes(int id_cou, int id_mes, string contentCom)
        //{

        //    if (ModelState.IsValid)
        //    {
        //        if (!String.IsNullOrEmpty(contentCom))
        //        {
        //            message com = new message();
        //            //com.id_com = id_com;
        //            com.id_cou = id_cou;
        //            com.content_mes = contentCom;
        //            com.createdate_msg = DateTime.Now;
        //            com.title_mes = null;
        //            com.parent = id_mes;
                    
        //            com.id_stu = null;
        //            com.isrepply = true;
                    
        //            db.messages.Add(com);
        //            db.SaveChanges();
        //        }
        //    }

        //    return RedirectToAction("Message_Detail", new { id_course = id_cou, id_mes = id_mes });
        //}
        public ActionResult Reply_msg(int id_cou, int id_msg, string contentMsg, IEnumerable<HttpPostedFileBase> fileuploads)
        {
            int id = WebSecurity.GetUserId(User.Identity.Name);
            var check = db.courses.Where(m => m.id_cou == id_cou && m.id_tea == id).Count();
            var msg = db.messages.Where(i => i.id_cou == id_cou && i.id_mes == id_msg);
            if (check <= 0 || msg == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!String.IsNullOrEmpty(contentMsg))
                    {
                        message msgs = new message();
                        msgs.id_cou = id_cou;
                        msgs.content_mes = contentMsg;
                        msgs.createdate_msg = DateTime.Now;
                        msgs.title_mes = null;
                        msgs.parent = id_msg;
                        string[] role = Roles.GetRolesForUser(User.Identity.Name);
                        if (role.Contains("Student"))
                        {
                            msgs.id_stu = id;
                            msgs.isrepply = false;
                        }
                        else
                        {
                            msgs.id_stu = null;
                            msgs.isrepply = true;
                        }
                        db.messages.Add(msgs);
                        db.SaveChanges();
                        int id_msg_reply = msgs.id_mes;
                        var dirName = encrypt(DateTime.Now.ToString());
                        var create_path = Server.MapPath("~/Content/FileUpload_message/" + User.Identity.Name + "/" + dirName);
                        foreach (HttpPostedFileBase fileupload in fileuploads)
                        {
                            if (fileupload != null && fileupload.ContentLength > 0)
                            {
                                var fileName = Path.GetFileName(fileupload.FileName);
                                var directory = new DirectoryInfo(create_path);

                                if (directory.Exists == false)
                                {
                                    directory.Create();
                                }
                                var path = Path.Combine(create_path, fileName);
                                fileupload.SaveAs(path);
                                file_attach file = new file_attach();
                                file.name = fileName;
                                file.source = "/Content/FileUpload_message/" + User.Identity.Name + "/" + dirName + "/" + fileName;
                                db.file_attach.Add(file);
                                db.SaveChanges();
                                int id_att = file.id_att;
                                message_file msg_file = new message_file();
                                msg_file.id_mes = id_msg_reply;
                                msg_file.id_att = id_att;
                                db.message_file.Add(msg_file);
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            return RedirectToAction("Message_Detail", new { id_course = id_cou, id_mes = id_msg });
        }
        public static string encrypt(string x)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            //compute hash from the bytes of text
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(x));

            //get hash result after compute it
            byte[] result = md5.Hash;

            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                //change it into 2 hexadecimal digits
                //for each byte
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
    }

}
